package com.by_man.presenter.module_health_management.measure_blood_pressure;

import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.module_bluetooth.DeviceScanActivity;
import com.by_man.presenter.module_bluetooth.OmronHem;
import com.by_man.presenter.main_page.MainActivity;
import com.by_man.repository.IpAddress;
import com.by_man.repository.LocalDataManager;
import com.by_man.repository.NetworkDataManager;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * 血压测量Activity
 * Created by man on 2017-02-11.
 */
public class MeasureBloodPressureActivity extends AppCompatActivity {
    WebView bloodPressureWebView;
    WebView heartRateWebView;

    TextView bloodPressureHigh;
    TextView bloodPressureLow;
    TextView heartRate;
    TextView measureTime;
    TextView type;

    private Handler handler;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_measure_blood_pressure);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                initView();
            }
        };
        if (null == UserInfos.One_BloodPressure_Record) { // 开启线程
            progressDialog = new ProgressDialog(this);
            progressDialog.setTitle("提示信息");
            progressDialog.setMessage("正在请求数据，请稍后......");
            progressDialog.setCancelable(false);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.show();
            if (NetworkDataManager.OneBPNum < 1) {  // 对此请求后，询问用户
                showRequestAgain();
            }
            Thread thread = new Thread() {
                public void run() {
                    while (null == UserInfos.One_BloodPressure_Record) {  // 阻塞等待数据的初始化
                        if (NetworkDataManager.OneBPNum < 1) {
                            showRequestAgain();
                        }
                    }
                    progressDialog.dismiss();
                    Message message = Message.obtain(handler);
                    message.sendToTarget();
                }
            };
            thread.setDaemon(true);             // 设置为守护线程
            thread.start();
        }
        else {
            initView();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_measure, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
//                Intent intent = new Intent(this, MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                startActivity(intent);
                onBackPressed();
                break;
            case R.id.action_check:
                Intent intent_B = new Intent(this, CheckBloodPressureActivity.class);
//                intent_B.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent_B);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            Intent intent = new Intent(this, MainActivity.class);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//            startActivity(intent);
//        }
//        return super.onKeyDown(keyCode,event);
//    }

    private void initView() {
        // 设定toolbar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        // 初始化webview
        bloodPressureWebView = (WebView) findViewById(R.id.blood_pressure_web_view);
        heartRateWebView = (WebView) findViewById(R.id.heart_rate_web_view);
        String ipAddressBloodPressure = getResources().getString(R.string.bp_webview_loadaddress_init) +
                "?token=" + UserInfos.token;
        settingWebView(bloodPressureWebView, ipAddressBloodPressure);

        String ipAddressHeartRate = getResources().getString(R.string.hr_webview_loadaddress_init) +
                "?token=" + UserInfos.token;
        settingWebView(heartRateWebView, ipAddressHeartRate);

        // 为单选框组注册监听
        RadioGroup showSetting = (RadioGroup)findViewById(R.id.rg_blood_pressure);
        showSetting.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                String addressBloodPressure,addressHeartRate;
                if(R.id.month_record == checkedId) {
                    addressBloodPressure = getResources().getString(R.string.bp_webview_loadaddress_month) +
                            "?token=" + UserInfos.token;
                    addressHeartRate = getResources().getString(R.string.hr_webview_loadaddress_month) +
                            "?token=" + UserInfos.token;
                    bloodPressureWebView.loadUrl(addressBloodPressure);
                    heartRateWebView.loadUrl(addressHeartRate);
                }
                else if(R.id.two_week_record == checkedId) {
                    addressBloodPressure = "http://" + IpAddress.ServerIP +
                            "/api/tests/select/fourteen/xueya?token=" + UserInfos.token;
                    addressHeartRate = "http://" + IpAddress.ServerIP +
                            "/api/tests/select/fourteen/xinlv?token=" + UserInfos.token;
                    bloodPressureWebView.loadUrl(addressBloodPressure);
                    heartRateWebView.loadUrl(addressHeartRate);
                }
                else if(R.id.week_record == checkedId) {
                    addressBloodPressure = getResources().getString(R.string.bp_webview_loadaddress_init) +
                            "?token=" + UserInfos.token;
                    addressHeartRate = getResources().getString(R.string.hr_webview_loadaddress_init) +
                            "?token=" + UserInfos.token;
                    bloodPressureWebView.loadUrl(addressBloodPressure);
                    heartRateWebView.loadUrl(addressHeartRate);
                }
                else {

                }

                if (R.id.proportion == checkedId) {
                    addressBloodPressure = getResources().getString(R.string.high_webview_loadaddress_proportion) +
                            "?token=" + UserInfos.token;
                    addressHeartRate = getResources().getString(R.string.low_webview_loadaddress_proportion) +
                            "?token=" + UserInfos.token;
                    bloodPressureWebView.loadUrl(addressBloodPressure);
                    heartRateWebView.loadUrl(addressHeartRate);
                }
            }
        });

        // 获取服务器中的血压心率信息
        bloodPressureHigh = (TextView)findViewById(R.id.blood_pressure_high);
        bloodPressureLow = (TextView)findViewById(R.id.blood_pressure_low);
        heartRate = (TextView)findViewById(R.id.heart_rate);
        measureTime = (TextView)findViewById(R.id.measure_time);
        type = (TextView)findViewById(R.id.type);
        // 如何保证一定能取出信息，如果不能给出提示，并在此请求
        JSONArray jsonArray = LocalDataManager.getOneBloodPressureRecord();
        if (null != jsonArray) {
            try {
                JSONObject jsonObject = jsonArray.getJSONObject(0);
                // 取出信息
                measureTime.setText(jsonObject.getString("updated_at").substring(0, 16));
                bloodPressureHigh.setText(jsonObject.getString("value"));
                if (jsonObject.getString("type").equalsIgnoreCase("null")) {
                    type.setText("未知");
                } else if(jsonObject.getString("type").equalsIgnoreCase("0")) {
                    type.setText("来自手动输入");
                } else {
                    type.setText("来自蓝牙输入");
                }
                jsonObject = jsonArray.getJSONObject(1);
                bloodPressureLow.setText(jsonObject.getString("value"));
                jsonObject = jsonArray.getJSONObject(2);
                heartRate.setText(jsonObject.getString("value"));
            } catch(JSONException e) {
                Log.i("Exception", e.toString());
                e.printStackTrace();
            }
        }

        Button manualBtn = (Button) findViewById(R.id.manual_button);
        manualBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MeasureBloodPressureActivity.this, ManualInputBPActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        Button bluetoothBtn = (Button)findViewById(R.id.bluetooth_button);
        bluetoothBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(MeasureBloodPressureActivity.this)
                        .setTitle("请选择设备类型")
                        .setPositiveButton("家康", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(MeasureBloodPressureActivity.this, DeviceScanActivity.class);
//                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            }
                        })
                        .setNegativeButton("欧姆龙", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                Intent intent = new Intent(MeasureBloodPressureActivity.this, OmronHem.class);
//                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            }
                        }).show();
            }
        });
    }

    // 对webview进行相关设置
    private void settingWebView(WebView webView,String ipAddress) {
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webView.getSettings().setAppCacheEnabled(false);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl(ipAddress);
    }

    public void showRequestAgain() {
        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this).setTitle("提醒")
                .setMessage("已多次请求服务器，是否继续请求？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        NetworkDataManager.OneBPNum = 3;
                        LocalDataManager.getOneBloodPressureRecord();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                }).create();
        alertDialog.show();
    }

//    protected void onRestart()
//    {
//        super.onRestart();
//        Intent intent=new Intent(this,GestureLockActivity.class);
//        intent.putExtra("class",this.getClass().getName());
//        intent.putExtra("position", 0);
//        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//        startActivity(intent);
//    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
